class AIChatApp {
    constructor() {
        // 检查登录状态
        this.checkLogin();
        
        this.messageInput = document.getElementById('messageInput');
        this.sendButton = document.getElementById('sendButton');
        this.chatMessages = document.getElementById('chatMessages');
        this.messageHistory = [];
        this.isWaitingResponse = false; // 添加响应等待标志

        this.init();

        // 添加欢迎消息
        if (this.chatMessages.children.length === 0) {
            this.addMessage('您好！我是财资企业知识助手，请问有什么可以帮您？', 'ai');
        }
    }

    checkLogin() {
        const isLoggedIn = localStorage.getItem('isLoggedIn');
        if (!isLoggedIn) {
            // 如果未登录，重定向到登录页面
            window.location.href = 'login.html';
            return;
        }
    }

    init() {
        this.sendButton.addEventListener('click', () => this.handleSendMessage());
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.handleSendMessage();
            }
        });

        // 加载历史消息
        this.loadMessageHistory();
    }

    // 新增处理发送消息的方法
    handleSendMessage() {
        if (this.isWaitingResponse) {
            // 如果正在等待响应，显示提示
            this.showTempMessage('AI 正在响应中，请稍候再发送新的问题');
            return;
        }
        this.sendMessage();
    }

    // 显示临时提示消息
    showTempMessage(message) {
        const tempDiv = document.createElement('div');
        tempDiv.className = 'temp-message';
        tempDiv.textContent = message;
        this.chatMessages.appendChild(tempDiv);
        
        // 3秒后自动删除提示
        setTimeout(() => {
            tempDiv.remove();
        }, 3000);
    }

    async loadMessageHistory() {
        try {
            // 这里可以调用后端接口获取历史消息
            // const response = await fetch('/api/message-history');
            // const history = await response.json();
            // this.messageHistory = history;
            // this.displayMessages(history);
        } catch (error) {
            console.error('加载历史消息失败:', error);
        }
    }

    async sendMessage() {
        const message = this.messageInput.value.trim();
        if (!message) return;

        this.isWaitingResponse = true;
        this.sendButton.disabled = true;

        const messageId = Date.now();
        this.addMessage(message, 'user', messageId);
        this.messageInput.value = '';

        let startTime = Date.now();
        const updateWaitingTime = () => {
            const waitingTime = Math.floor((Date.now() - startTime) / 1000);
            const waitingElement = document.getElementById(`waiting-${messageId}`);
            if (waitingElement) {
                waitingElement.textContent = `等待响应中... ${waitingTime}秒`;
            }
            // 检查是否超时
            if (waitingTime >= 60) {
                clearInterval(timer);
                this.handleTimeout(messageId);
                controller.abort(); // 中断请求
            }
        };
        
        this.addWaitingIndicator(messageId);
        const timer = setInterval(updateWaitingTime, 1000);

        // 创建 AbortController 用于超时取消请求
        const controller = new AbortController();

        try {
            const response = await fetch('http://127.0.0.1:8086/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    question: message
                }),
                signal: controller.signal
            });

            if (!response.ok) {
                throw new Error('网络请求失败');
            }

            const answer = await response.text();
            const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);
            
            clearInterval(timer);
            this.removeWaitingIndicator(messageId);
            
            this.addMessage(answer || '无回复内容', 'ai', messageId);

        } catch (error) {
            clearInterval(timer);
            this.removeWaitingIndicator(messageId);
            
            console.error('发送消息失败:', error);
            if (error.name === 'AbortError') {
                return;
            }
            this.addMessage('抱歉，发生了错误，请稍后重试。', 'ai', null);
        } finally {
            this.isWaitingResponse = false;
            this.sendButton.disabled = false;
        }
    }

    // 修改超时处理方法
    handleTimeout(messageId) {
        this.removeWaitingIndicator(messageId);
        // 超时消息不需要 messageId，这样就不会显示反馈按钮
        this.addMessage('抱歉，响应时间过长，请稍后重试。', 'ai', null);
        this.isWaitingResponse = false;
        this.sendButton.disabled = false;
    }

    addMessage(content, type, messageId = null, responseTime = null) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}-message`;
        if (messageId) {
            messageDiv.id = `message-${messageId}`;
        }
        
        if (type === 'ai') {
            // 添加头像和名称到消息框外
            const headerDiv = document.createElement('div');
            headerDiv.className = 'message-header';
            headerDiv.innerHTML = `
                <img src="images/cz_title.jpg" class="avatar" alt="财小资">
                <span class="agent-name">财小资(财小资)</span>
            `;
            messageDiv.appendChild(headerDiv);
        }
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        
        if (type === 'ai') {
            // 添加消息文本
            const textDiv = document.createElement('div');
            textDiv.className = 'message-text';
            
            marked.setOptions({
                breaks: true,
                gfm: true,
                emoji: true
            });
            
            let htmlContent = marked.parse(content);
            textDiv.innerHTML = htmlContent;
            messageContent.appendChild(textDiv);

            // 只在非欢迎消息时添加反馈部分
            if (messageId) {  // messageId 存在表示是问答消息，而不是欢迎消息
                const footerDiv = document.createElement('div');
                footerDiv.className = 'message-footer';
                
                const feedbackDiv = document.createElement('div');
                feedbackDiv.className = 'feedback-section';
                feedbackDiv.innerHTML = `
                    <span class="feedback-question">该回答是否可信？</span>
                    <div class="feedback-buttons">
                        <button class="feedback-btn yes" onclick="handleFeedback(this, true)">
                            👍 是
                        </button>
                        <button class="feedback-btn no" onclick="handleFeedback(this, false)">
                            👎 否
                        </button>
                    </div>
                `;
                footerDiv.appendChild(feedbackDiv);
                messageContent.appendChild(footerDiv);
            }
        } else {
            messageContent.textContent = content;
        }
        
        messageDiv.appendChild(messageContent);
        this.chatMessages.appendChild(messageDiv);
        
        this.messageHistory.push({
            content,
            type,
            messageId,
            responseTime,
            timestamp: new Date().toISOString()
        });

        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    addWaitingIndicator(messageId) {
        const waitingDiv = document.createElement('div');
        waitingDiv.className = 'waiting-indicator';
        waitingDiv.id = `waiting-${messageId}`;
        waitingDiv.textContent = '等待响应中... 0秒';
        
        const messageElement = document.getElementById(`message-${messageId}`);
        if (messageElement) {
            messageElement.appendChild(waitingDiv);
        }
    }

    removeWaitingIndicator(messageId) {
        const waitingElement = document.getElementById(`waiting-${messageId}`);
        if (waitingElement) {
            waitingElement.remove();
        }
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new AIChatApp();
});

// 添加退出登录函数
function logout() {
    localStorage.removeItem('isLoggedIn');
    window.location.href = 'login.html';
}

function handleFeedback(button, isPositive) {
    const buttons = button.parentElement.querySelectorAll('.feedback-btn');
    buttons.forEach(btn => {
        btn.classList.remove('selected');
    });
    button.classList.add('selected');
    
    // 这里可以添加反馈上报逻辑
    console.log(`用户反馈: ${isPositive ? '可信' : '不可信'}`);
}

// 确保函数是全局可用的
window.handleFeedback = handleFeedback; 